<template>
	<view class="content">
		<!-- 搜索 -->
		<view class="top-search">
			<image class="left" src="../../static/common/left.png" @tap="goSignIn"></image>
			<view class="center">
				<image src="../../static/common/search.png" class="search-icon"></image>
				<input type="text" disabled="disabled" placeholder="复制宝贝标题快速搜索" @tap="gosearch" class="uni-input search-input" placeholder-class="input-placeholder" />
			</view>
			<image class="right" src="../../static/common/right.png" @tap="goMessage"></image>
		</view>
		
		<scroll-view  scroll-y="true" 
		class="scroll-Y scroll-box"
		 @scroll="scroll" 
		 lower-threshold="100" 
		 :scroll-top="scrollTop"
		 
		 refresher-enabled="true" :refresher-triggered="triggered"
		 :refresher-threshold="100" 
		 @refresherrefresh="onRefresh" @refresherrestore="onRestore" 
		 
		 @scrolltolower="loadMore">
			<!-- swiper -->
			<view class="page-section swiper">
				<view class="page-section-spacing">
						<swiper class="swiper" :indicator-dots="indicatorDots" :circular="circular" :autoplay="autoplay" :interval="interval" :duration="duration">
								<!-- <swiper-item>
									<image src="../../static/common/home-swiper-pic1.png" @tap="goNewDriver"></image>
								</swiper-item> -->
								<swiper-item>
									<image src="../../static/common/banner-02.png"></image>
								</swiper-item>
						</swiper>
				</view>
			</view>
			<!-- 4个分类 -->
			<view class="four-classification">
				<image src="../../static/common/classification-goods.png" class="classification-goods" @tap="goGoodsClassification"></image>
				<image v-show=" main && main_inviteId > 0" src="../../static/common/classification-superfan.png" class="classification-superfan" @tap="goSuperBack"></image>	
				<image v-show=" !main || main_inviteId < 1" src="../../static/common/joinus.png" class="joinus" @tap="joinus"></image>
				
			<!-- 	<image v-show=" main " src="../../static/common/classification-superfan.png" class="classification-superfan" @tap="goSuperBack"></image>
				<image v-show=" !main " src="../../static/common/joinus.png" class="joinus" @tap="joinus"></image> -->
				
				<image src="../../static/common/classification-99b.png" class="classification-99b" @tap="goSpecialArea"></image>
				<image src="../../static/common/classification-newuser.png" class="classification-newuser" @tap="goNewDriver"></image>
			</view>
			
			<!-- 充话费送小孩 -->
			<view class="echarge" v-if="newArticle" @tap="articalDetail(newArticle.articleId)">
				<image src="../../static/common/recharge-icon.png" class="recharge-icon"></image>
				<view class="recharge-text">
					{{newArticle? newArticle.title : "暂无最新公告"}}
				</view>
			</view>
			
			<!-- nav-bar -->
			<view class="scroll-navbar-box" :class="isFixed? 'isfixed' : ''">
				<view class="scroll-view_H">
					<view class="nav-bar-item "
					v-for="(item,k) in goodsClass" 
					:key="k"
					:class="{'selected-bar':currentIndex == k}"
					@tap.prevent="getGoodList(item,k,'initPage')"
					>{{item}}</view>
				</view>
			</view>
			
			<view class="box" v-if="loading">
			    <view class="loader-15"></view>
			</view>
			<!-- 商品列表 -->
			<view class="goods-list">
				<good v-for="(item,index) in goodList" :key="index" :goodsInfo="item" @goodsDetail="goodsDetail"></good>
			</view>
			<image src="../../static/common/scroll-top-tk.png" class="scroll-top-img" v-if="isFixed" @tap="gotop"></image>
		</scroll-view>
	
		<!-- 隐私政策 -->
		<!-- <view class="yinsi-block">
			
		</view> -->
		 <lyg-popup @popupState="popupState" title="服务协议" protocolPath='../user/privacy_policy'
		         policyPath='../user/privacy_policy' policyStorageKey="has_read_privacy"></lyg-popup>
		    </view>
	</view>
</template>

<script>
	const util = require('../../util/util.js');
	const plug= uni.requireNativePlugin('UZK-Alibcsdk');
	import good from '../../components/goods/good.vue'
	import {myMixins} from '../../common/mixins.js'
	import lyg_popup from '@/components/lyg-popup/lyg-popup.vue';
	export default {
		mixins:[myMixins],
		data() {
			return {
				currentIndex:0,  //Nav-bar,选中id
				currentGoodsClass:"推荐",
				//navList:[],
				indicatorDots: false,
				autoplay: true,
				circular:true,
				interval: 2000,
				duration: 500,
				isFixed:false,
				page_no:1,//当前页数
				goodList:[],//商品列表
				goodsClass:["推荐"],//商品分类
				scrollTop:-1,//回到顶部标识
				noData:false, //加载更多数据标识
				// apptoken:"",
				//inviteId:"",
				userId:"",
				newArticle:"",//最新公告
				loading:false,
				main:"",
				main_inviteId:"",
				triggered: true,
				freshing:false,
			}
		},
		components:{
			good,lyg_popup
		},
		onLoad(){
			uni.showLoading();
			//this.loadExecution();
			//this.navList =this.$Data.HomeNavBar;
			//推荐商品
			this.getGoodList();
			//获取商品分类
			this.getGoodsClass();
			//获取用户使用设备信息
			//this.$store.dispatch('getDevice');
			//最新公告
			this.getnewArticle();
			//客服
			this.getKeFu();
			//var apptoken = "";
			this.getApptoken();
			//this.apptoken = uni.getStorageSync("apptoken");
			//this.inviteId = uni.getStorageSync("inviteId");
			this.userId = uni.getStorageSync("userId");
			//缓存浏览记录
			const history = uni.getStorageSync("HistoryFoot");
			if(!history){
				uni.setStorage({
					key:"HistoryFoot",
					data:[]
				})
			}
			//main
			
		},
		onShow() {
			const _this = this;
			if(uni.getStorageSync("apptoken")){
				uni.request({
					url:this.$API.URL + this.$API.main,
					data:{apptoken:uni.getStorageSync("apptoken")},
					success(res) {
						console.log(res)
						if(res.data.success){
							_this.main = true;
							_this.main_inviteId = res.data.data.inviteId;
						}else{
							_this.main = false;
						}
					}
				})
			}
		},
		methods: {
			popupState(state) {
					console.log(state);
			},
			onRefresh() {
					if (this.freshing) return;
					this.freshing = true;
					
					this.getGoodList(this.currentGoodsClass,this.currentIndex,'initPage','refsh')
					
			},
			onRestore() {
					this.triggered = 'restore'; // 需要重置
			},
			joinus(){
				if(!uni.getStorageSync("apptoken")){
					uni.navigateTo({
						url:'../login/login',
						animationType:'slide-in-bottom',
					})
				}else{
					uni.navigateTo({
						url:'../user/share-panda'
					})
				}
			},
			
			getMain(){
				const _this = this;
				uni.request({
					url:this.$API.URL + this.$API.main,
					data:{apptoken:this.apptoken},
					success(res) {
						console.log(res)
						if(!res.data.success){
							_this.main = false;
							return;
						}else{
							_this.main = true;
						}
					}
				})
			},
			getKeFu(){
				uni.request({
					url:this.$API.URL + this.$API.kefu,
					data:{apptoken:this.apptoken},
					success(res) {
						console.log(res)
						if(res.data.success){
							uni.setStorage({
								key:"kefu",
								data:res.data.data
							})
						}
					}
				})
			},
			getnewArticle(){
				//获取最新公告
				const _this = this;
				uni.request({
					url:this.$API.URL + this.$API.newArticle,
					// data:{
					// 	apptoken:this.apptoken,
					// },
					success(res){
						console.log(res)
						if(res.data.data){
							_this.newArticle = res.data.data;
						}else{
							_this.newArticle = '';
						}
						
					}
				})
			},
			articalDetail(articleId){
				//查看公告详情
				if(uni.getStorageSync("apptoken")){
					this.$CommonJS.navigateTo('../message/messageDetail?articleId='+articleId);
				}else{
					uni.navigateTo({
						url:'../login/login',
						animationType:'slide-in-bottom',
					})
				}
				
				
			},
			autoTbao(){
				this.$once('autoTbao',function(code,state){
					console.log("触发了监听事件");
					console.log(code+state);
				})
			},
			getApptoken(){
				const _this = this;
				
				//const userId = uni.getStorageSync("userId");
				//console.log(apptoken + userId);
			},
			goodsDetail(id){
				//console.log(coupon)
				//商品详情
					this.$CommonJS.navigateTo('../goodDetail/good-detail?id='+id);
				//this.$CommonJS.navigateTo('../goodDetail/good-detail?coupon='+coupon.coupon+'&startTime='+coupon.startTime+'&endTime='+coupon.endTime);
			},
			//商品分类
			getGoodsClass(){
				const self = this;
				uni.request({
				    url: this.$API.URL + this.$API.spk_cate,
				    success: (res) => {
							//console.log(res)
							const d = res.data.msg.data;
							d.map(item => {
								self.goodsClass.push(item.name)
							})
							//console.log(self.goodsClass)
				    }
				});
			},
			//防抖事件//商品分页
			loadMore: util.throttle(function(e) {
				this.getGoodList()
			}, 300),
			//推荐商品
			getGoodList(name,index,initPage,refsh){
				const _this = this;
				this.loading = true;
				if(initPage){
					this.currentGoodsClass = name;
					this.page_no = 1;//初始化页数
					this.noData = false; // 将判断有无数据标识初始化
					this.scrollTop = 0; //回到顶部
				}
				if(index){
					this.currentIndex = index; //当前选中标识
				}
				var self = this;
				var url = ""; //定义url,推荐和其他类目不是一个接口
				var data = ""; //请求参数
				if(this.currentGoodsClass == "推荐" || name == "推荐"){
					//推荐商品		
					this.currentIndex = 0;
					url = this.$API.URL + this.$API.spk_top;
					data = {min_id:this.page_no};
				}else{
					
					url = this.$API.URL + this.$API.tbk_super_search;
					data = {q:this.currentGoodsClass,page_no:this.page_no};
				}
				if(!this.noData){
					//如果没有数据，则停止访问接口，再次请求数据
					uni.request({
					    url: url,
							data:data,
					    success: (res) => {
								const d = res.data.msg;
								//console.log(res)
								if(d.code == 200){
									self.loading = false;
									uni.hideLoading();
									_this.triggered = false;
									_this.freshing = false;
									if(name){
										self.goodList = []; //如name存在，说明是从新加载类目商品，置空，否则为分页
									}
									d.data.map(item => {
										self.goodList.push(item)
									})
									self.page_no ++;
									self.scrollTop = -1; //回到顶部标识
									if(refsh){
										uni.showToast({
											title:"刷新成功",
											icon:'none'
										})
									}
								}else{
									self.noData = true;
									_this.triggered = false;
									_this.freshing = false;
								}
								
					    },
							fail(res) {
								 uni.hideLoading();
								_this.triggered = false;
								_this.freshing = false;
								uni.showToast({
									title:res.data.msg,
									icon:'none'
								})
							}
					});
				}
				
			},
			gotop(){
				this.scrollTop = 0; //回到顶部
			},
			//9.9包邮
			goSpecialArea(){
				this.$CommonJS.navigateTo('../specialArea/specialArea');
			},
			//新手上路
			goNewDriver(){
				//if(this.checkLoginStatus()){
				if(uni.getStorageSync('apptoken')){
					
				  this.$CommonJS.navigateTo('../newDriver/newDriver');
				}else{
					uni.navigateTo({
						url:'../login/login',
						animationType:'slide-in-bottom',
					})
				}
				
			},
			//商品分类
			goGoodsClassification(){
				this.$CommonJS.navigateTo('../goodsClassification/goodsClassification');
			},
			//签到中心
			goSignIn(){
				
				//if(this.checkLoginStatus()){
				if(uni.getStorageSync('apptoken')){
						this.$CommonJS.navigateTo('../signIn/signin');
				}else{
					uni.navigateTo({
						url:'../login/login',
						animationType:'slide-in-bottom',
					})
				}
				
			},
			//消息中心
			goMessage:function(){
				//if(this.checkLoginStatus()){
				if(uni.getStorageSync('apptoken')){
					this.$CommonJS.navigateTo('../message/message');
				}else{
					uni.navigateTo({
						url:'../login/login',
						animationType:'slide-in-bottom',
					})
				}
				
			},
			//搜索页面
			gosearch:function(){
				this.$CommonJS.navigateTo('../search/search');
			},
			goSuperBack(){
				//超级返
				var apptoken = uni.getStorageSync("apptoken");
				if(!uni.getStorageSync("apptoken")){
					uni.navigateTo({
						url:'../login/login',
						animationType:'slide-in-bottom',
					})
					return;
				}
				//this.$CommonJS.navigateTo('../superBack/super-back');
				const _this = this;
				//判断用户是否进行了淘宝授权
				//let isAutoTbao = uni.getStorageSync('isAutoTbao');
				/*if(!isAutoTbao){
				// 	//淘宝未授权
					// uni.showModal({
					// 	title:"温馨提示",
					// 	content:"您还没有进行淘宝授权,请先授权才可以进入超级返",
					// 	success(res) {
					// 		if(res.confirm){
					// 			//授权登录
					// 			//#ifdef APP-PLUS
					// 				plus.runtime.openURL("https://oauth.taobao.com/authorize?response_type=code&client_id=28869937&redirect_uri=https://pandayoupin.com/panda.htm&state=1212&view=wap");
					// 			//#endif
					// 			//#ifdef H5
					// 			window.location.href="https://oauth.taobao.com/authorize?response_type=code&client_id=28869937&redirect_uri=https://pandayoupin.com/panda.htm&state=1212&view=wap";
					// 			//#endif
					// 		}
					// 	}
					// })
					
					//初始化
					plug.init(result=>{
					 if(result.status){
						 console.log("初始化成功");
						 //拉起手淘授权
						  plug.login(res=>{
								console.log(res)
								if(res.status){
					
									//登录成功
									_this.OauthInfo =  res.data;
									
									//拉起淘客静默授权
									plug.qdByhide({
									  url:"https://oauth.taobao.com/authorize?response_type=code&client_id=28869937&redirect_uri=https://pandayoupin.com/panda.htm&state=1212&view=wap",
										
									},result=> {
										console.log(result)
										uni.request({
											url:_this.$API.URL + _this.$API.getRelation_id,
											data:{
												code:result.data.code,
												state:result.data.state,
												apptoken:_this.apptoken,
												userId:_this.userId
											},
											success(res) {
												console.log(res)
												if(res.data.success){
													uni.setStorage({
														key:"isAutoTbao",
														data:true,
														success() {
															uni.showToast({
																title:"授权成功"
															})
														}
													})
													
												}else{
													uni.showModal({
														title:"淘宝授权失败",
														content:res.data.msg
													})
												}
											},
											fail(res) {
												uni.showToast({
													title:"授权失败"
												})
											}
										})
									});
								}else{
									_this.$CommonJS.showToast(res.msg)
								}
						  });  
					 }else{
						 console.log("初始化失败");
						 _this.$CommonJS.showToast(result.msg)
					 }
					});  
					
					return;
				}*/
				uni.request({
					url:this.$API.URL + this.$API.main,
					data:{apptoken:apptoken},
					success(res) {
						console.log(res);
						if(res.data.success){
							uni.setStorage({
								key:"mainInfo",
								data:res.data.data
							})
							if(!res.data.data.phone){
								uni.showModal({
									title:"温馨提示",
									content:"请先绑定手机号",
									success(res) {
										if(res.confirm){
											uni.navigateTo({
												url:'../user/user-info'
											})
										}
									}
								})
								return;
							}
							if(res.data.data.tongxunlu !== 1){
								//通信录授权
								uni.showModal({
									title:"温馨提示",
									content:"进入超级返,需要授权通讯录才可以哦",
									success(res) {
										if(res.confirm){
											var contactsArry = {};
											//#ifdef APP-PLUS
												//获取手机通讯录
													plus.contacts.getAddressBook( plus.contacts.ADDRESSBOOK_PHONE, function( addressbook ) {
														// 可通过addressbook进行通讯录操作
														//console.log(addressbook)
														addressbook.find(["displayName","phoneNumbers"],function(contacts){
															//console.log("phone="+contacts);
															contactsArry.PHONE = contacts;
														}, function () {
															console.log("error");
														},{multiple:true});
														
													}, function ( e ) {
														//取消授权
														console.log( "Get address book failed: " + e.message );
														return;
													} );
												//获取SIM卡通信录
												plus.contacts.getAddressBook( plus.contacts.ADDRESSBOOK_SIM, function( addressbook ) {
													// 可通过addressbook进行通讯录操作
													//console.log(addressbook)
													addressbook.find(["displayName","phoneNumbers"],function(contacts){
														//console.log("SIM="+contacts);
														contactsArry.SIM = contacts;
														
														
														_this.$nextTick(_this.updataContact(encodeURI(JSON.stringify(contactsArry)) ))
													}, function () {
														console.log("error");
													},{multiple:true});
													
												}, function ( e ) {
													//取消授权
													console.log( "Get address book failed: " + e.message );
													return;
												} );
												
												
												
											
												
											//#endif
										}else if(res.cancel){
											return;
										}
									}
								})
							}else{
								_this.$CommonJS.navigateTo('../superBack/super-back');
							}
							
						}else{
							_this.$CommonJS.showToast(res.data.msg)
						}
					}
				})
				
			},
			updataContact(contact){
				
				const _this = this;
				var apptoken = uni.getStorageSync("apptoken");
				uni.request({
					url:_this.$API.URL + _this.$API.tongxunlu,
					data:{apptoken:apptoken,phones:contact},
					method:"POST",
					header:{
						"content-type":"application/x-www-form-urlencoded"
					},
					success(res) {
						console.log(res)
						if(res.data.success){
							//通讯录提交成功，跳转超级返
							_this.$CommonJS.navigateTo('../superBack/super-back');
						}else{
							_this.$CommonJS.showToast(res.data.msg)
							console.log(res.data.msg)
						}
					}
				})
				
			},
			//导航栏固定在顶部
			scroll:function(event){
				//console.log(event.detail)
				if(event.detail.scrollTop >219){
					this.isFixed = true;
				}else{
					this.isFixed = false;
				}
			},
			loadExecution: function(){
				/**
				 * 获取本地存储中launchFlag的值
				 * 若存在，说明不是首次启动，直接进入首页；
				 * 若不存在，说明是首次启动，进入引导页；
				 */
				/*const value = uni.getStorageSync('apptoken');
				if(value){
					uni.switchTab({
					    url: '/pages/home/home'
					});
				}else{
					uni.navigateTo({
						url: '/pages/login/login'
					})
				}*/
			}
		}
	}
</script>
<style>
		@import "home.css";
		.box {
			margin: 0 auto;
		    /* display: inline-block; */
		   width: 100%;
		    height: auto;
				display: flex;
				flex-direction: row;
				justify-content: center;
				align-items: center;
		   /* border: 1px solid currentcolor;
		    border-radius: 3px; */
		    font-size: 30px;
		    color: rgba(200, 200, 200, 0.5);
		    /* padding: 1em; */
		    margin: .3em 0;
		    vertical-align: top;
		    -webkit-transition: .3s color, .3s border;
		    transition: .3s color, .3s border;
		}
		.loader-15 {
		    background: currentcolor;
		    position: relative;
		    -webkit-animation: loader-15 0.5s ease-in-out infinite;
		    animation: loader-15 0.5s ease-in-out infinite;
		    -webkit-animation-delay: 0.4s;
		    animation-delay: 0.4s;
		    width: .25em;
		    height: .5em;
		}
		.loader-15:after,
		.loader-15:before {
		    content: '';
		    position: absolute;
		    width: inherit;
		    height: inherit;
		    background: inherit;
		    -webkit-animation: inherit;
		    animation: inherit;
		}
		.loader-15:before {
		    right: .5em;
		    -webkit-animation-delay: 0.2s;
		    animation-delay: 0.2s;
		}
		.loader-15:after {
		    left: .5em;
		    -webkit-animation-delay: 0.6s;
		    animation-delay: 0.6s;
		}
		@-webkit-keyframes loader-15 {
		    0%, 100% {
		        box-shadow: 0 0 0 currentcolor, 0 0 0 currentcolor;
		    }
		    50% {
		        box-shadow: 0 -.25em 0 currentcolor, 0 .25em 0 currentcolor;
		    }
		}
		@keyframes loader-15 {
		    0%, 100% {
		        box-shadow: 0 0 0 currentcolor, 0 0 0 currentcolor;
		    }
		    50% {
		        box-shadow: 0 -.25em 0 currentcolor, 0 .25em 0 currentcolor;
		    }
		}
</style>
